package net.mgorski.log4jux.impl;

import net.mgorski.log4jux.Log;
import org.apache.log4j.Logger;

import java.util.Formatter;

/**
 * @author mgorski<mgorski.net>
 */
public class LogImpl implements Log {

  private final Formatter formatter = new Formatter();
  private final Logger logger;

  public LogImpl(Logger logger) {
    this.logger = logger;
  }

  @Override
  public void t(String formatMessage, Object... params) {
    if (logger.isTraceEnabled()) {
      logger.trace(format(formatMessage, params));
    }
  }

  @Override
  public void t(Throwable t, String formatMessage, Object... params) {
    if (logger.isTraceEnabled()) {
      logger.trace(format(formatMessage, params), t);
    }
  }

  @Override
  public void d(String formatMessage, Object... params) {
    if (logger.isDebugEnabled()) {
      logger.debug(format(formatMessage, params));
    }
  }

  @Override
  public void d(Throwable t, String formatMessage, Object... params) {
    if (logger.isDebugEnabled()) {
      logger.debug(format(formatMessage, params), t);
    }

  }

  @Override
  public void i(String formatMessage, Object... params) {
    if (logger.isInfoEnabled()) {
      logger.info(format(formatMessage, params));
    }

  }

  @Override
  public void i(Throwable t, String formatMessage, Object... params) {
    if (logger.isInfoEnabled()) {
      logger.info(format(formatMessage, params), t);
    }
  }

  @Override
  public void w(String formatMessage, Object... params) {
    logger.warn(format(formatMessage, params));
  }

  @Override
  public void w(Throwable t, String formatMessage, Object... params) {
    logger.warn(format(formatMessage, params), t);
  }

  @Override
  public void e(String formatMessage, Object... params) {
    logger.error(format(formatMessage, params));
  }

  @Override
  public void e(Throwable t, String formatMessage, Object... params) {
    logger.error(format(formatMessage, params), t);
  }

  @Override
  public void f(String formatMessage, Object... params) {
    logger.fatal(format(formatMessage, params));
  }

  @Override
  public void f(Throwable t, String formatMessage, Object... params) {
    logger.fatal(format(formatMessage, params), t);
  }


  /**
   * Formats the string using the params.
   * @param formatMessage
   * @param params
   * @return
   */
  private String format(String formatMessage, Object... params) {
    final StringBuilder sb = (StringBuilder) formatter.out();
    formatter.format(formatMessage, params);
    return sb.toString();
  }
}
